package org.ftz;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextScrollPane;
import org.ftz.JudgeOnline.CPP.ExecuteCLangService;
import org.ftz.JudgeOnline.Java.ExecuteJava;
import org.ftz.control.*;
import org.ftz.pojo.Problem;
import org.ftz.pojo.Status;
import org.ftz.pojo.Testcase;
import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper;
import sun.plugin2.message.JavaObjectOpMessage;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.List;
public class server extends MainFrame implements ActionListener, KeyListener, ChangeListener {
    public BufferedWriter bw=null;
    private static Socket socketAudio;
    public static OutputStream outAudio;
    private static InputStream inAudio;
    public static byte[] bos = new byte[2024];
    private static byte[] bis = new byte[2024];
    public static TargetDataLine targetDataLine;
    private static SourceDataLine sourceDataLine;
    private JTextArea area;
    public int a=0;
    public String input;
    public JTabbedPane tabbedPane1;
    public JLabel label;
    public JScrollPane jsp;
    public JPanel panel41;
    public JTextArea jTextArea;
    public JButton jButtoncb;
    public HashMap<String,JPanel> hashMap=new HashMap<>();
    public HashMap<String,JTextArea> textAreaHashMap=new HashMap<>();
    public HashMap<String,JButton> jButtonHashMap=new HashMap<>();
    public HashMap<String,Integer> integerHashMap=new HashMap<>();
    public HashMap<String,String> ipAndname=new HashMap<>();
    List<Socket> socketList=new ArrayList<>();
    List<Socket> socketListFile=new ArrayList<>();
    int flag=1;
    public String s;
    public String FileName;
    public String fullPath;
    Socket socketFile;
    DataOutputStream dataOutputStream=null;
    DataInputStream dataInputStream=null;
    public DefaultTableModel model;
    Page page=null;
    public JLabel show;
    public String choosePath;
    public JFrame detaliFrame;
    public JTable jTable;
    String a1="";
    public server() throws IOException, LineUnavailableException {
        mainFrame();
        mainFrame2();
        showMsg();
    }
    public static void main(String[] args) throws IOException, LineUnavailableException {
        try {
            org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
            UIManager.put("RootPane.setupButtonVisible",false);
            UIManager.put("TabbedPane.tabAreaInsets",new javax.swing.plaf.InsetsUIResource(0,0,2,20));
        }catch (Exception e){
            System.out.println("加载炫彩皮肤失败！");
        }
        server server = new server();
    }
    @Override
    public void mainFrame2() {
        panel3.setBounds(0, 0, 860, 550); //聊天界面实现
        panel3.setVisible(true);
        JPanel jLabel=new JPanel();
        Dimension dimension = new Dimension(860, 30);
        jLabel.setPreferredSize(dimension);
        Color color = new Color(1, 216, 254);
        jLabel.setBackground(color);
        label = new JLabel();
        Font font = new Font("微软雅黑", Font.BOLD, 18);
        label.setFont(font);
        label.setText("你与所有人的对话");
        jLabel.add(label);
        tabbedPane1=new JTabbedPane(JTabbedPane.RIGHT);
        jsp = new JScrollPane();
        Dimension dimension1 = new Dimension(840, 400);
        jsp.setPreferredSize(dimension1);
        panel41= new JPanel(null);
        panel41.setVisible(true);
        jsp.getViewport().add(panel41);
        jsp.validate();
        tabbedPane1.addTab("所有人",jsp);
        hashMap.put("所有人",panel41);
        integerHashMap.put("所有人",0);
        FlowLayout flowLayout = new FlowLayout();
        JPanel jPanel5=new JPanel(flowLayout);
        Box box2=Box.createHorizontalBox();
        jtf=new JTextArea(4,30);
        jb=new JButton("发送");
        ImageIcon imageIcon7 = new ImageIcon("src\\main\\java\\org\\ftz\\images\\发送消息.png");
        imageIcon7.setImage(imageIcon7.getImage().getScaledInstance(18,18,Image.SCALE_DEFAULT));
        jb.setIcon(imageIcon7);
        jTextArea=new JTextArea(4,30);
        Box box1=Box.createVerticalBox();
        JButton jButton2=new JButton("选择");
        ImageIcon imageIcon6 = new ImageIcon("src\\main\\java\\org\\ftz\\images\\文件夹.png");
        imageIcon6.setImage(imageIcon6.getImage().getScaledInstance(14,14,Image.SCALE_DEFAULT));
        jButton2.setIcon(imageIcon6);
        JButton jButton=new JButton("传输文件");
        box1.add(jButton2);
        box1.add(Box.createVerticalStrut(10));
        box1.add(jButton);
        box2.add(jTextArea);
        box2.add(Box.createHorizontalStrut(10));
        box2.add(box1);
        box2.add(Box.createHorizontalStrut(40));
        box2.add(jtf);
        box2.add(Box.createHorizontalStrut(10));
        box2.add(jb);
        jPanel5.add(box2);
        jPanel5.setBounds(0,450,860,100);
        Box box=Box.createVerticalBox();
        box.add(jLabel);
        box.add(tabbedPane1);
        box.add(Box.createVerticalStrut(15));
        box.add(jPanel5);
        panel3.add(box);
        tabbedPane = new JTabbedPane();
        JLabel tab1 = new JLabel();
        JLabel tab2 = new JLabel();
        JLabel tab3 = new JLabel();
        JLabel tab4=new JLabel();
        JLabel tab5=new JLabel();
        JLabel tab7=new JLabel();
        panel4s.add(tab4);
        panel1.add(tab1);
        panel2.add(tab2);
        panel3.add(tab3);
        panel5.add(tab5);
        panel7.add(tab7);
        ImageIcon imageIcon = new ImageIcon("src\\main\\java\\org\\ftz\\images\\3.1首页.png");
        imageIcon.setImage(imageIcon.getImage().getScaledInstance(16,16,Image.SCALE_DEFAULT));
        tabbedPane.addTab("首页",imageIcon,panel4s);
        ImageIcon imageIcon2 = new ImageIcon("src\\main\\java\\org\\ftz\\images\\在线测评.png");
        imageIcon2.setImage(imageIcon2.getImage().getScaledInstance(16,16,Image.SCALE_DEFAULT));
        tabbedPane.addTab("在线测评",imageIcon2,panel1);
        ImageIcon imageIcon1 = new ImageIcon("src\\main\\java\\org\\ftz\\images\\远程操控.png");
        imageIcon1.setImage(imageIcon1.getImage().getScaledInstance(16,16,Image.SCALE_DEFAULT));
        tabbedPane.addTab("远程操控",imageIcon1,panel2);
        ImageIcon imageIcon3 = new ImageIcon("src\\main\\java\\org\\ftz\\images\\对话.png");
        imageIcon3.setImage(imageIcon3.getImage().getScaledInstance(17,17,Image.SCALE_DEFAULT));
        tabbedPane.addTab("聊天",imageIcon3,panel3);
        ImageIcon imageIcon4 = new ImageIcon("src\\main\\java\\org\\ftz\\images\\在线测评 (1).png");
        imageIcon4.setImage(imageIcon4.getImage().getScaledInstance(17,17,Image.SCALE_DEFAULT));
        tabbedPane.addTab("OJ系统",imageIcon4,panel7);
        ImageIcon imageIcon5 = new ImageIcon("src\\main\\java\\org\\ftz\\images\\帮助与说明.png");
        imageIcon5.setImage(imageIcon5.getImage().getScaledInstance(18,18,Image.SCALE_DEFAULT));
        tabbedPane.addTab("说明",imageIcon5,panel5);
        JPanel panels=new JPanel();
        panels.add(tabbedPane);
        jf.setContentPane(panels);
        jb.addActionListener(this); //给发送按钮添加点击事件
        jtf.addKeyListener(this); //给文本框添加键盘点击事件
        tabbedPane.addChangeListener(this);
        tabbedPane1.addChangeListener(this);
        jf.setVisible(true);
        jButton2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser jFileChooser=new JFileChooser();
                jFileChooser.showOpenDialog(null);
                s = jFileChooser.getSelectedFile().toString();
                String name = jFileChooser.getSelectedFile().getName();
                System.out.println(s);
                System.out.println(name);
                FileName=name;
                jTextArea.setText(name);
            }
        });
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendFile();
                System.out.println("传输");
                jTextArea.setText("");
            }
        });
    }
    public void mainFrame(){
        super.mainFrame1();
        panel2.setLayout(null);
        area = new JTextArea();
        area.setBounds(300,100,300,200);
        area.setEditable(false);
        jButtoncb=new JButton("开启语音");
        jButtoncb.setBounds(380,320,120,30);
        jButtoncb.setVisible(true);
        panel2.add(area);
        panel2.add(jButtoncb);
        panel4s.setLayout(null);
        JLabel jLabel=new JLabel("程序设计远程协助系统");
        jLabel.setBounds(170,170,700,50);
        jLabel.setFont(new Font("楷体",Font.BOLD,60));
        JLabel jLabel1=new JLabel("教师端");
        jLabel1.setBounds(660,240,200,40);
        jLabel1.setFont(new Font("楷体",Font.BOLD,40));
        panel4s.add(jLabel);
        panel4s.add(jLabel1);
        panel5.setLayout(null);
        JLabel jLabel2=new JLabel("本系统教师端功能如下：");
        jLabel2.setBounds(0,0,700,40);
        jLabel2.setFont(new Font("楷体",Font.BOLD,25));
        JLabel jLabel3=new JLabel("1.在线测评：输入c/c++,java代码即可在线编译运行得出结果");
        jLabel3.setBounds(0,40,900,40);
        jLabel3.setFont(new Font("楷体",Font.BOLD,25));
        JLabel jLabel4=new JLabel("2.远程操控：学生端连接到教师端后，教师可以查看学生端程序内容并进行修改");
        jLabel4.setBounds(0,80,1000,40);
        jLabel4.setFont(new Font("楷体",Font.BOLD,25));
        JLabel jLabel5=new JLabel("，同时支持语音交流，另外允许多个学生端同时连接到一台教师机上");
        jLabel5.setBounds(0,120,1000,40);
        jLabel5.setFont(new Font("楷体",Font.BOLD,25));
        JLabel jLabel6=new JLabel("3.聊天：首先输入昵称，然后可以进行文字交流和文件传输");
        jLabel6.setBounds(0,160,1000,40);
        jLabel6.setFont(new Font("楷体",Font.BOLD,25));
        JLabel jLabel7=new JLabel("(1)文字交流：教师可以和多名同学进行文字的发送与接受");
        jLabel7.setBounds(0,200,1000,40);
        jLabel7.setFont(new Font("楷体",Font.BOLD,25));
        JLabel jLabel8=new JLabel("(2)文件传输：教师可以将本地文件发送给一个或多个学生同时可以接收学生发送");
        jLabel8.setBounds(0,240,1000,40);
        jLabel8.setFont(new Font("楷体",Font.BOLD,25));
        JLabel jLabel9=new JLabel("的文件");
        jLabel9.setBounds(0,280,1000,40);
        jLabel9.setFont(new Font("楷体",Font.BOLD,25));
        JLabel jLabel10=new JLabel("4.OJ系统");
        jLabel10.setBounds(0,320,1000,40);
        jLabel10.setFont(new Font("楷体",Font.BOLD,25));
        JLabel jLabel11=new JLabel("教师端可以增加题目，删除题目，以及题目的展示，同时支持c/c++,java等编译");
        jLabel11.setBounds(0,360,1000,40);
        jLabel11.setFont(new Font("楷体",Font.BOLD,25));
        panel5.add(jLabel2);
        panel5.add(jLabel3);
        panel5.add(jLabel4);
        panel5.add(jLabel5);
        panel5.add(jLabel6);
        panel5.add(jLabel7);
        panel5.add(jLabel8);
        panel5.add(jLabel9);
        panel5.add(jLabel10);
        panel5.add(jLabel11);
        panel7.setLayout(null);
        JLabel label=new JLabel("Problem List");
        label.setFont(new Font("楷体",Font.BOLD,20));
        label.setBounds(10,0,140,40);
        label.setBackground(Color.GREEN);
        panel7.add(label);
        JButton add=new JButton("添加题目");
        ImageIcon imageIcon = new ImageIcon("src\\main\\java\\org\\ftz\\images\\添加.png");
        imageIcon.setImage(imageIcon.getImage().getScaledInstance(12,12,Image.SCALE_DEFAULT));
        add.setIcon(imageIcon);
        add.setBounds(700,5,85,30);
        panel7.add(add);
        add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFrame addtimu=new JFrame("添加题目");
                addtimu.setResizable(false);
                addtimu.setLocationRelativeTo(null);
                addtimu.setSize(950,650);
                Rectangle jfBounds = server.super.jf.getBounds();
                int width=addtimu.getWidth();
                int height=addtimu.getHeight();
                int x=jfBounds.x+(jfBounds.width-width)/2;
                int y=jfBounds.y+(jfBounds.height-height)/2;
                addtimu.setBounds(x,y,width,height);
                JPanel panel=new JPanel(null);
                JLabel id=new JLabel("编号");
                id.setFont(new Font("微软雅黑",Font.BOLD,18));
                id.setBounds(20,10,50,30);
                panel.add(id);
                JTextField jTextField=new JTextField(5);
                jTextField.setFont(new Font("宋体",Font.PLAIN,16));
                jTextField.setBounds(65,10,60,30);
                panel.add(jTextField);
                JLabel title=new JLabel("题目");
                title.setFont(new Font("微软雅黑",Font.BOLD,18));
                title.setBounds(170,10,50,30);
                panel.add(title);
                JTextField jTextField1=new JTextField(30);
                jTextField1.setFont(new Font("宋体",Font.PLAIN,16));
                jTextField1.setBounds(220,10,250,30);
                panel.add(jTextField1);
                JLabel leval=new JLabel("难度");
                leval.setFont(new Font("微软雅黑",Font.BOLD,18));
                leval.setBounds(520,10,50,30);
                panel.add(leval);
                JComboBox jComboBox2=new JComboBox();
                jComboBox2.setFont(new Font("宋体",Font.PLAIN,16));
                jComboBox2.addItem("Low");
                jComboBox2.addItem("Mid");
                jComboBox2.addItem("High");
                jComboBox2.setBounds(570,10,100,30);
                panel.add(jComboBox2);
                JLabel description=new JLabel("题目描述");
                description.setFont(new Font("微软雅黑",Font.BOLD,18));
                description.setBounds(20,60,100,30);
                panel.add(description);
                JTextArea textArea=new JTextArea(15,10);
                JScrollPane scrollPane1=new JScrollPane(textArea);
                textArea.setWrapStyleWord(true);
                textArea.setFont(new Font("微软雅黑",Font.PLAIN,16));
                scrollPane1.setBounds(15,100,860,350);
                JLabel test=new JLabel("测试用例");
                test.setFont(new Font("宋体",Font.BOLD,18));
                test.setBounds(20,460,100,30);
                panel.add(test);
                JLabel testFile=new JLabel("Choose File");
                ImageIcon imageIcon = new ImageIcon("src\\main\\java\\org\\ftz\\images\\上传.png");
                imageIcon.setImage(imageIcon.getImage().getScaledInstance(25,25,Image.SCALE_DEFAULT));
                testFile.setIcon(imageIcon);
                testFile.setOpaque(true);
                testFile.setForeground(Color.WHITE);
                testFile.setBackground(new Color(53,163,217));
                testFile.setFont(new Font("微软雅黑",Font.PLAIN,16));
                Border border = testFile.getBorder();
                Border emptyBorder = new EmptyBorder(10, 10, 10, 10);
                testFile.setBorder(new CompoundBorder(border,emptyBorder));
                testFile.setBounds(110,460,140,30);
                panel.add(testFile);
                JTextField jTextField2=new JTextField(25);
                jTextField2.setFont(new Font("宋体",Font.PLAIN,16));
                jTextField2.setBounds(270,460,180,30);
                panel.add(jTextField2);
                JButton save=new JButton("Save");
                save.setBounds(480,460,100,30);
                save.setFont(new Font("微软雅黑",Font.PLAIN,18));
                panel.add(save);
                testFile.addMouseListener(new MouseListener() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        System.out.println("点击");
                        JFileChooser jFileChooser=new JFileChooser();
                        jFileChooser.showOpenDialog(null);
                        choosePath = jFileChooser.getSelectedFile().getAbsolutePath();
                        jTextField2.setText(jFileChooser.getSelectedFile().getName());
                        System.out.println(choosePath);
                    }
                    @Override
                    public void mousePressed(MouseEvent e) {
                    }
                    @Override
                    public void mouseReleased(MouseEvent e) {
                    }
                    @Override
                    public void mouseEntered(MouseEvent e) {
                    }
                    @Override
                    public void mouseExited(MouseEvent e) {
                    }
                });
                save.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String id=jTextField.getText(); //编号
                        String title=jTextField1.getText(); //题目
                        String leval = jComboBox2.getSelectedItem().toString(); //等级
                        String description = textArea.getText(); //描述
                        try {
                            List<String> fileList = util.getZipFileList(choosePath);
                            Problem problem = new Problem(Integer.valueOf(id),title,leval,description,"");
                            Testcase testCase1 = new Testcase(Integer.valueOf(id), fileList.get(0), fileList.get(1));
                            String res = AddTimu(problem, testCase1);
                            System.out.println("结果："+res);
                            int confirmDialog = JOptionPane.showConfirmDialog(addtimu, "添加题目成功！", "添加题目", JOptionPane.YES_NO_OPTION);
                            if(confirmDialog==JOptionPane.YES_OPTION){
                                addtimu.dispose();
                                showTable(1);
                                show.setText("当前是第1页/共"+page.getLastPage()+"页");
                            }
                        } catch (IOException | SQLException ioException) {
                            ioException.printStackTrace();
                        }
                    }
                });
                panel.add(scrollPane1);
                addtimu.setContentPane(panel);
                addtimu.setVisible(true);
            }
        });
        String[] columnNames={"题目编号","题目名称","等级"};
        model=new DefaultTableModel(columnNames,0);
        jTable = new JTable(model){
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        JScrollPane jScrollPane=new JScrollPane();
        jScrollPane.setViewportView(jTable);
        jTable.setRowHeight(40);
        jTable.setFont(new Font("宋体",Font.PLAIN,16));
        jTable.getColumnModel().getColumn(0).setPreferredWidth(180);
        jTable.getColumnModel().getColumn(1).setPreferredWidth(400);
        jTable.getColumnModel().getColumn(2).setPreferredWidth(200);
        jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        jTable.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int row = jTable.getSelectedRow();
                int col=jTable.getSelectedColumn();
                int id=(int)jTable.getValueAt(row,0);
                if(col==0){
                    System.out.println(id);
                    Problem problem = selectBId(id);
                    System.out.println(problem.getDescription());
                    detaliFrame =new JFrame();
                    detaliFrame.setTitle("题目详情("+id+")");
                    detaliFrame.setResizable(false);
                    detaliFrame.setLocationRelativeTo(null);
                    detaliFrame.setSize(950,650);
                    Rectangle jfBounds = server.super.jf.getBounds();
                    int width=detaliFrame.getWidth();
                    int height=detaliFrame.getHeight();
                    int x=jfBounds.x+(jfBounds.width-width)/2;
                    int y=jfBounds.y+(jfBounds.height-height)/2;
                    detaliFrame.setBounds(x,y,width,height);
                    JPanel panel=new JPanel(null);
                    JTextArea textArea=new JTextArea(10,10);
                    JScrollPane scrollPane1=new JScrollPane(textArea);
                    textArea.setWrapStyleWord(true);
                    textArea.setFont(new Font("微软雅黑",Font.BOLD,16));
                    textArea.setText(problem.getDescription());
                    textArea.setEditable(false);
                    scrollPane1.setBounds(10,10,860,250);
                    JLabel language=new JLabel("Language:");
                    language.setFont(new Font("微软雅黑",Font.BOLD,18));
                    language.setBounds(20,265,100,30);
                    JComboBox jComboBox2=new JComboBox();
                    jComboBox2.addItem("C");
                    jComboBox2.addItem("C++");
                    jComboBox2.addItem("Java");
                    jComboBox2.setBounds(120,265,100,30);
                    JButton submit=new JButton("Submit");
                    ImageIcon imageIcon1 = new ImageIcon("src\\main\\java\\org\\ftz\\images\\写.png");
                    imageIcon1.setImage(imageIcon1.getImage().getScaledInstance(14,14,Image.SCALE_DEFAULT));
                    submit.setIcon(imageIcon1);
                    submit.setBounds(280,265,95,30);
                    submit.setFont(new Font("微软雅黑",Font.PLAIN,16));
                    JButton clear=new JButton("Clear");
                    ImageIcon imageIcon2 = new ImageIcon("src\\main\\java\\org\\ftz\\images\\清空 (2).png");
                    imageIcon2.setImage(imageIcon2.getImage().getScaledInstance(16,16,Image.SCALE_DEFAULT));
                    clear.setIcon(imageIcon2);
                    clear.setBounds(400,265,80,30);
                    clear.setFont(new Font("微软雅黑",Font.PLAIN,16));
                    panel.add(clear);
                    JLabel shows=new JLabel("Pending");
                    shows.setOpaque(true);
                    shows.setBackground(new Color(255,153,0));
                    shows.setForeground(Color.WHITE);
                    shows.setFont(new Font("微软雅黑",Font.PLAIN,16));
                    Border border = shows.getBorder();
                    Border emptyBorder = new EmptyBorder(10, 10, 10, 10);
                    shows.setBorder(new CompoundBorder(border,emptyBorder));
                    shows.setBounds(600,265,93,30);
                    shows.setVisible(false);
                    panel.add(shows);
                    JPanel cp=new JPanel();
                    cp.setBounds(10,300,860,270);
                    RSyntaxTextArea textArea1 = new RSyntaxTextArea(15, 112);
                    textArea1.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_CPLUSPLUS);
                    textArea1.setCodeFoldingEnabled(true);
                    RTextScrollPane sp = new RTextScrollPane(textArea1);
                    cp.add(sp);
                    panel.add(scrollPane1);
                    panel.add(language);
                    panel.add(submit);
                    panel.add(jComboBox2);
                    panel.add(cp);
                    detaliFrame.setContentPane(panel);
                    detaliFrame.setVisible(true);
                    clear.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            textArea1.setText("");
                            shows.setVisible(false);
                        }
                    });
                    submit.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            String code=textArea1.getText();
                            System.out.println(jComboBox2.getSelectedIndex());
                            System.out.println(jComboBox2.getSelectedItem().toString());
                            shows.setVisible(true);
                            if(jComboBox2.getSelectedIndex()==0||jComboBox2.getSelectedIndex()==1){
                                String ip = "";
                                try {
                                    ip= InetAddress.getLocalHost().getHostAddress();
                                } catch (UnknownHostException unknownHostException) {
                                    unknownHostException.printStackTrace();
                                }
                                String out="";
                                shows.setVisible(true);
                                org.ftz.JudgeOnline.question.ExecuteCLangService executeCLangService=new org.ftz.JudgeOnline.question.ExecuteCLangService();
                                out = executeCLangService.runCLangCode(code,id);
                                System.out.println("out："+out);
                                String showTag = "";
                                if(out.equals("成功")){
                                    showTag="Accepted";
                                    shows.setBackground(new Color(25,190,107));
                                    shows.setText(showTag);
                                    shows.setVisible(true);
                                }else if(out.equals("答案错误")){
                                    showTag="Wrong Answer";
                                    shows.setText(showTag);
                                    shows.setBackground(new Color(237,63,20));
                                    shows.setSize(134,30);
                                    shows.setVisible(true);
                                }else if(out.equals("编译出错")){
                                    showTag="Compile Error";
                                    shows.setText(showTag);
                                    shows.setBackground(new Color(255,153,0));
                                    shows.setSize(130,30);
                                    shows.setVisible(true);
                                }
                                Status status = new Status(ip,id,showTag,jComboBox2.getSelectedItem().toString(),new Date());
                                try {
                                    insertStatus(status);
                                } catch (UnknownHostException unknownHostException) {
                                    unknownHostException.printStackTrace();
                                }
                                System.out.println("showTag："+showTag);
                            }
                        }
                    });
                }else if(col==2){
                    jTable.addMouseListener(new MouseListener() {
                        @Override
                        public void mouseClicked(MouseEvent e) {
                            if(e.getButton()==MouseEvent.BUTTON3){
                                System.out.println("题目编号："+a1);
                                JPopupMenu popupMenu=new JPopupMenu();
                                JMenuItem jMenuItem=new JMenuItem("删除");
                                popupMenu.add(jMenuItem);
                                popupMenu.show(jTable,e.getX(),e.getY());
                                jMenuItem.addActionListener(new ActionListener() {
                                    @Override
                                    public void actionPerformed(ActionEvent e) {
                                        System.out.println("删除"+id);
                                        int confirmDialog = JOptionPane.showConfirmDialog(jTable, "请确认你要删除题号为" + id + "的题目？",
                                                "删除题目", JOptionPane.YES_NO_OPTION);
                                        if(confirmDialog==JOptionPane.YES_OPTION){
                                            deletebyId(id);
                                            System.out.println(id+"删除成功");
                                            showTable(1);
                                            show.setText("当前是第1页/共"+page.getLastPage()+"页");
                                        }
                                    }
                                });
                            }
                        }
                        @Override
                        public void mousePressed(MouseEvent e) {
                        }
                        @Override
                        public void mouseReleased(MouseEvent e) {
                        }
                        @Override
                        public void mouseEntered(MouseEvent e) {
                        }
                        @Override
                        public void mouseExited(MouseEvent e) {
                        }
                    });
                }
            }
            @Override
            public void mousePressed(MouseEvent e) {
            }
            @Override
            public void mouseReleased(MouseEvent e) {
            }
            @Override
            public void mouseEntered(MouseEvent e) {
            }
            @Override
            public void mouseExited(MouseEvent e) {
            }
        });
        jScrollPane.setBounds(10,40,800,450);
        panel7.add(jScrollPane);
        page = new Page();
        int column = getColumn();
        if(column%page.getPageSize()==0){
            page.setLastPage(column/page.getPageSize());
        }else {
            page.setLastPage(column/page.getPageSize()+1);
        }
        showTable(1);
        JButton fitst=new JButton("首页");
        fitst.setBounds(100,500,60,30);
        fitst.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                show.setText("当前是第1页/共"+page.getLastPage()+"页");
                showTable(1);
            }
        });
        JButton prex=new JButton("上一页");
        prex.setBounds(200,500,60,30);
        prex.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(page.getCurrentPage()<=1){
                    page.setCurrentPage(2);
                    show.setText("当前是第1页/共"+page.getLastPage()+"页");
                }
                showTable(page.getCurrentPage()-1);
                show.setText("当前是第"+(page.getCurrentPage())+"页/共"+page.getLastPage()+"页");
            }
        });
        JButton next=new JButton("下一页");
        next.setBounds(300,500,60,30);
        next.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(page.getCurrentPage()<page.getLastPage()){
                    showTable(page.getCurrentPage()+1);
                    show.setText("当前是第"+(page.getCurrentPage())+"页/共"+page.getLastPage()+"页");
                }else {
                    show.setText("当前是第"+page.getLastPage()+"页/共"+page.getLastPage()+"页");
                    showTable(page.getLastPage());
                }
            }
        });
        JButton last=new JButton("尾页");
        last.setBounds(400,500,60,30);
        last.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                show.setText("当前是第"+page.getLastPage()+"页/共"+page.getLastPage()+"页");
                showTable(page.getLastPage());
            }
        });
        show=new JLabel("当前是第1页/共"+page.getLastPage()+"页");
        show.setBounds(500,500,120,30);
        panel7.add(fitst);
        panel7.add(prex);
        panel7.add(next);
        panel7.add(last);
        panel7.add(show);
        cleanBtn.addActionListener(this);
        runBtn.addActionListener(this);
        clearAll.addActionListener(this);
        jButtoncb.addActionListener(this);
        new Thread(new receive(socketList)).start();
    }
    public void insertStatus(Status status) throws UnknownHostException { //插入一条做题状态
        Connection connection = null;
        PreparedStatement statement =null;
        String ip= InetAddress.getLocalHost().getHostAddress();
        try {
            connection = DBUtil.getConnection(); // 1. 建立连接
            String sql = "insert into oj_status values(?,?,?,?,?)";  // 2. 拼装 SQL 语句
            statement = connection.prepareStatement(sql);
            statement.setString(1,status.getIp());
            statement.setInt(2,status.getId());
            statement.setString(3,status.getStatus());
            statement.setString(4,status.getLanguage());
            long time=status.getTime().getTime();
            statement.setTimestamp(5,new java.sql.Timestamp(time) );
            int ret = statement.executeUpdate(); // 3. 执行 SQL 语句
            if(ret == 1){
                System.out.println("插入成功!");
            }else {
                System.out.println("插入失败!");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,null);
        }
    }
    public void repaintMessage(String str) {
        String str1 = area.getText();
        System.out.println(str1);
        area.setText(str1 + "\n" + str);
    }
    public void showMsg() throws IOException, LineUnavailableException {
        repaintMessage("读取配置");
        ServerSocket server = null;
        try {
            server = new ServerSocket(5000);
        } catch (IOException e) {
            e.printStackTrace();
            repaintMessage("端口启动异常" + e.getMessage());
            return;
        }
        repaintMessage("服务器已经正常启动");
        repaintMessage("本机地址端口:" +util.getHostIp() + ":" + 5000);
        repaintMessage("监听客户端");
        while (true){
            ClientWindow cw;
            DataInputStream dis;
            Socket socket=server.accept();
            System.out.println("eregt");
            System.out.println("有客户端连接，地址:" + socket.getInetAddress().getHostAddress());
            repaintMessage("有客户端连接，地址:" + socket.getInetAddress().getHostAddress());
            InputStream inputStream = socket.getInputStream();
            dis = new DataInputStream(inputStream);
            OutputStream outputStream = socket.getOutputStream();
            String hostAddress = socket.getInetAddress().getHostAddress();
            cw = new ClientWindow(outputStream, socket.getInputStream(),hostAddress);
            new Thread(new ReceiveImage(cw,dis)).start();
        }
    }
    @Override
    public void stateChanged(ChangeEvent e) {
        System.out.println(e.getSource());
        String title = tabbedPane.getTitleAt(tabbedPane.getSelectedIndex());
        System.out.println("tabbedPane:"+title);
        if(title.equals("聊天")&&flag==1){
            input=JOptionPane.showInputDialog("请输入昵称：");
            System.out.println(input);
            jf.setTitle("程序设计远程协助系统(教师端-"+input+")");
            flag=0;
            new Thread(new receiveFile(socketListFile)).start();
        }
        int index = tabbedPane1.getSelectedIndex();
        System.out.println("tabbedPane1:"+index);
        String titleAt = tabbedPane1.getTitleAt(tabbedPane1.getSelectedIndex());
        String names=titleAt;
        if(titleAt.contains('('+"")||titleAt.contains(')'+"")){
            names=titleAt.substring(0,titleAt.indexOf('('));
            tabbedPane1.setTitleAt(index,names);
        }
        label.setText("你与"+names+"的对话");
    }
    public class Page{ //分页展示
        public int currentPage=1;
        public int pageSize=10;
        public int lastPage;
        public int getCurrentPage() {
            return currentPage;
        }
        public void setCurrentPage(int currentPage) {
            this.currentPage = currentPage;
        }
        public int getPageSize() {
            return pageSize;
        }
        public void setPageSize(int pageSize) {
            this.pageSize = pageSize;
        }
        public int getLastPage() {
            return lastPage;
        }
        public void setLastPage(int lastPage) {
            this.lastPage = lastPage;
        }
    }
    public String AddTimu(Problem problem, Testcase testCase) throws SQLException { //添加题目
        Connection connection=null;
        PreparedStatement statement=null;
        PreparedStatement statement2=null;
        try {
            connection=DBUtil.getConnection();
            String sql1="insert into oj_problem values(?,?,?,?,?)";
            String sql2="insert into oj_test values(?,?,?)";
            statement=connection.prepareStatement(sql1);
            statement2=connection.prepareStatement(sql2);
            statement.setInt(1,problem.getId());
            statement.setString(2,problem.getTitle());
            statement.setString(3,problem.getLevel());
            statement.setString(4,problem.getDescription());
            statement.setString(5,"");
            statement2.setInt(1,testCase.getId());
            statement2.setString(2,testCase.getInput());
            statement2.setString(3,testCase.getOutput());
            int res=statement.executeUpdate();
            int res2=statement2.executeUpdate();
            if(res==1&&res2==1){
                System.out.println("插入成功！");
                return "插入成功";
            }else {
                System.out.println("插入失败！");
                return "插入失败";
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,null);
            statement2.close();
        }
        return "未知错误";
    }
    public void deletebyId(int id){ //删除题目
        Connection connection = null;
        PreparedStatement statement = null;
        PreparedStatement statement1=null;
        try {
            connection = DBUtil.getConnection(); // 1. 建立连接
            String sql = "delete from oj_problem where id = ?"; // 2. 拼装 SQL 语句
            String sql2="delete from oj_test where id = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,id);
            statement1=connection.prepareStatement(sql2);
            statement1.setInt(1,id);
            int ret = statement.executeUpdate(); // 3. 执行 SQL 语句
            int res=statement1.executeUpdate();
            if(ret == 1&&res==1){
                System.out.println("删除成功!");
            }else {
                System.out.println("删除失败!");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection,statement,null); // 4. 关闭释放资源
        }
    }
    public void showTable(int currentPage){ //分页展示
        model.setRowCount(0);
        page.setCurrentPage(currentPage);
        int offset=(currentPage-1)*page.getPageSize();
        int rows=page.getPageSize();
        List<Problem> problems = selectLimit(offset, rows);
        for(int row=0;row<problems.size();row++){
            Vector vector=new Vector();
            Problem problem=problems.get(row);
            vector.add(problem.getId());
            vector.add(problem.getTitle());
            vector.add(problem.getLevel());
            model.addRow(vector);
        }
    }
    public List<Problem> selectLimit(int a, int b){ //分页查询问题
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Problem> list = new ArrayList<>();
        try {
            connection = DBUtil.getConnection(); // 1. 建立连接
            String sql = "select id,title,level from oj_problem limit ?,?";  // 2. 拼装 SQL 语句
            statement = connection.prepareStatement(sql);
            statement.setInt(1,a);
            statement.setInt(2,b);
            resultSet = statement.executeQuery(); // 3. 执行 SQL 语句
            while (resultSet.next()){  // 4. 遍历结果集
                Problem problem = new Problem();
                problem.setId(resultSet.getInt("id"));
                problem.setTitle(resultSet.getString("title"));
                problem.setLevel(resultSet.getString("level"));
                list.add(problem);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet); // 5. 关闭释放资源
        }
        for(Problem problem:list){
            System.out.println(problem);
        }
        return list;
    }
    public Problem selectBId(int id){ //根据题目编号查询题目
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        Problem problem = new Problem();
        try {
            connection = DBUtil.getConnection(); // 1. 建立连接
            String sql = "select * from oj_problem where id=?"; // 2. 拼装 SQL 语句
            statement = connection.prepareStatement(sql);
            statement.setInt(1,id);
            resultSet = statement.executeQuery(); // 3. 执行 SQL 语句
            while (resultSet.next()){ // 4. 遍历结果集
                problem.setId(resultSet.getInt("id"));
                problem.setTitle(resultSet.getString("title"));
                problem.setLevel(resultSet.getString("level"));
                problem.setDescription(resultSet.getString("description"));
                problem.setTestcasepath(resultSet.getString("testcasepath"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet); // 5. 关闭释放资源
        }
        return problem;
    }
    public int getColumn(){ //获取题目数量
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        int rowCount=0;
        try {
            connection = DBUtil.getConnection();  // 1. 建立连接
            String sql = "select count(*) from oj_problem";  // 2. 拼装 SQL 语句
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();// 3. 执行 SQL 语句
            if(resultSet.next()){  // 4. 遍历结果集
                rowCount=resultSet.getInt(1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet);// 5. 关闭释放资源
        }
        System.out.println(rowCount);
        return rowCount;
    }
    class receiveFile implements Runnable{
        List<Socket> socketListFile;
        public receiveFile(List<Socket> socketListFile) {
            this.socketListFile = socketListFile;
        }
        @Override
        public void run() {
            ServerSocket serverSocketFile=null;
            try {
                serverSocketFile=new ServerSocket(3999);
                System.out.println("监听客户端接受文件程序");
                while (true){
                    Socket socket12=serverSocketFile.accept();
                    socketListFile.add(socket12);
                    new Thread(new ShouFile(socket12,socketListFile)).start();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    class ReceiveImage implements Runnable{
        ClientWindow cw;
        DataInputStream dis;
        public ReceiveImage(ClientWindow cw, DataInputStream dis) {
            this.cw = cw;
            this.dis = dis;
        }
        @Override
        public void run() {
            byte[] imageBytes;
            while (true) {
                try {
                    imageBytes = new byte[dis.readInt()]; // 先拿到传过来的数组长度
                    dis.readFully(imageBytes); // 所有的数据存放到byte中
                    cw.repainImage(imageBytes);
                } catch (IOException e) {
                }
            }
        }
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        String code = codeArea.getText();
        String inputAreaText = inputArea.getText();
        if(e.getActionCommand().equals("清空")){
            codeArea.setText("");
            System.out.println(jComboBox.getSelectedIndex());
        }else if(e.getActionCommand().equals("点击运行")&&(jComboBox.getSelectedIndex()==0)){
            util.writeFile(inputAreaText);
            ExecuteCLangService executeCLangService = new ExecuteCLangService();
            String out = executeCLangService.runCLangCode(code);
            System.out.println("输出："+out);
            String[] split = out.split("@");
            outputArea.setText(split[0]+System.lineSeparator());
            outputArea.append(split[1]);
        }else if(e.getActionCommand().equals("点击运行")&&(jComboBox.getSelectedIndex()==1)){
            String output = ExecuteJava.runJava(code, inputAreaText);
            String[] split = output.split("@");
            outputArea.setText(split[0]+System.lineSeparator());
            outputArea.append(split[1]);
        } else if(e.getActionCommand().equals("发送")){
            System.out.println("hello");
            senddata();
        }else if(e.getActionCommand().equals("清空所有")){
            codeArea.setText("");
            inputArea.setText("");
            outputArea.setText("");
        }else if(e.getActionCommand().equals("开启语音")){
            System.out.println("开启语音");
            jButtoncb.setText("关闭语音");
            OutputStream outAudio = null;
            InputStream inAudio=null;
            TargetDataLine targetDataLine=null;
            SourceDataLine sourceDataLine=null;
            Socket socketAudio=null;
            try {
                ServerSocket serverAudio = new ServerSocket(5001);
                socketAudio = serverAudio.accept();
                System.out.println("语音连接成功");
                outAudio = socketAudio.getOutputStream();  //打开语音
                inAudio= socketAudio.getInputStream();
                targetDataLine = AudioUtils.getTargetDataLine();
                sourceDataLine = AudioUtils.getSourceDataLine();
                System.out.println("server:");
                new Thread(new SendAudio(bos,targetDataLine,outAudio)).start();
                new Thread(new ReceiveAudio(bis,inAudio,sourceDataLine)).start();
            } catch (Exception ioException) {
                ioException.printStackTrace();
            }
        }
        else if(e.getActionCommand().equals("关闭语音")){
            jButtoncb.setText("开启语音");
            try {
                outAudio.close();
                inAudio.close();
                socketAudio.shutdownInput();
                socketAudio.shutdownOutput();
                socketAudio.close();
                socketAudio=null;
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
    }
    @Override
    public void keyTyped(KeyEvent e) { }
    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode()==KeyEvent.VK_ENTER){ //回车键
            senddata();
        }
    }
    @Override
    public void keyReleased(KeyEvent e) { }
    public void sendFile(){
        System.out.println("--------------");
        System.out.println(socketListFile);
        System.out.println("--------------");
        String names=input;
        String namesL=names.substring(names.length()-2);
        String text="《"+FileName+"》已经发送！";
        String titles = tabbedPane1.getTitleAt(tabbedPane1.getSelectedIndex()); //聊天的客户端名字
        JLabel msglabel=new JLabel(text+System.lineSeparator());  //消息
        Font font = new Font("微软雅黑", Font.BOLD, 18);
        msglabel.setFont(font);
        msglabel.setForeground(Color.WHITE);
        Color color = new Color(1, 153, 255);
        msglabel.setBackground(color);
        msglabel.setSize(840,30);
        msglabel.setOpaque(true);
        FlowLayout flowLayout = new FlowLayout(); //装消息面板（每一行一个）
        JPanel itempanel=new JPanel(flowLayout);
        FlowLayout layout = (FlowLayout) itempanel.getLayout();
        layout.setAlignment(FlowLayout.RIGHT);
        JButton jButton=new RoundButton(namesL);
        Insets insets = new Insets(-5, -5, -5, -5);
        jButton.setMargin(insets);
        Font font1 = new Font("微软雅黑", Font.BOLD, 18);
        jButton.setFont(font1);
        Dimension dimension = new Dimension(48, 48);
        jButton.setPreferredSize(dimension);
        jButton.setBackground(Color.BLUE);
        jButton.setForeground(Color.WHITE);
        GridLayout gridLayout = new GridLayout(2, 1);
        JPanel panelL=new JPanel(gridLayout);
        JLabel label=new JLabel(names);
        label.setHorizontalAlignment(SwingConstants.RIGHT);
        panelL.add(label);
        panelL.add(msglabel);
        Color color1 = new Color(250, 250, 250);
        itempanel.setBackground(color1);
        System.out.println(titles);
        Integer integer = integerHashMap.get(titles);
        System.out.println(integer);
        itempanel.setBounds(0,integer,840,55);
        integer+=60;
        integerHashMap.replace(titles,integer);
        itempanel.add(panelL);
        itempanel.add(jButton);
        JPanel jPanel = hashMap.get(titles);
        jPanel.add(itempanel);
        jPanel.updateUI();
        Dimension dimension1 = new Dimension(840, integer);
        jPanel.setPreferredSize(dimension1);
        socketListFile.forEach(socket1 -> {
            System.out.println(socket1);
            try {
                System.out.println(socket1.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            File file = new File(s);
            try {
                OutputStream outputStream = socket1.getOutputStream();
                dataOutputStream=new DataOutputStream(outputStream);
                FileInputStream fileInputStream = new FileInputStream(s);
                dataInputStream=new DataInputStream(fileInputStream);
                int bufferSize=1024;
                int count=-1,sum=0;
                byte[] bufArray = new byte[bufferSize*bufferSize];
                String title = tabbedPane1.getTitleAt(tabbedPane1.getSelectedIndex()); //聊天的客户端名字
                String sendData=title.length()+title+"@"+file.getName(); //发送内容：客户端
                dataOutputStream.writeUTF(sendData);
                dataOutputStream.writeLong((long)file.length());
                while ((count=dataInputStream.read(bufArray))!=-1){
                    dataOutputStream.write(bufArray,0,count);
                    sum+=count;
                    System.out.println("以传输"+sum+"byte");
                }
                System.out.println("发送完毕");
                dataOutputStream.flush();
            }catch (Exception e){
                e.printStackTrace();
            }
        });
        System.out.println(socketListFile);
    }
    public void senddata(){
        String name=input; //获得文本框内容
        String nameL=name.substring(name.length()-2);
        String title = tabbedPane1.getTitleAt(tabbedPane1.getSelectedIndex()); //聊天的客户端名字
        String text = jtf.getText(); //文本
        String sendtext="@"+title.length()+title+"#"+name.length()+name+text; //@+客户端姓名长度+客户端姓名+#+服务端姓名长度+服务端姓名+文本
        System.out.println(sendtext);
        JLabel msglabel=new JLabel(text+System.lineSeparator()); //消息
        Font font = new Font("微软雅黑", Font.BOLD, 18);
        msglabel.setFont(font);
        msglabel.setForeground(Color.WHITE);
        Color color = new Color(1, 153, 255);
        msglabel.setBackground(color);
        msglabel.setSize(840,30);
        msglabel.setOpaque(true);
        FlowLayout flowLayout = new FlowLayout(); //装消息面板（每一行一个）
        JPanel itempanel=new JPanel(flowLayout);
        FlowLayout layout = (FlowLayout) itempanel.getLayout();
        layout.setAlignment(FlowLayout.RIGHT);
        JButton jButton=new RoundButton(nameL);
        Insets insets = new Insets(-5, -5, -5, -5);
        jButton.setMargin(insets);
        Font font1 = new Font("微软雅黑", Font.BOLD, 18);
        jButton.setFont(font1);
        Dimension dimension = new Dimension(48, 48);
        jButton.setPreferredSize(dimension);
        jButton.setBackground(Color.BLUE);
        jButton.setForeground(Color.WHITE);
        GridLayout gridLayout = new GridLayout(2, 1);
        JPanel panelL=new JPanel(gridLayout);
        JLabel label=new JLabel(name);
        label.setHorizontalAlignment(SwingConstants.RIGHT);
        panelL.add(label);
        panelL.add(msglabel);
        itempanel.setBackground(new Color(250,250,250));
        System.out.println(title);
        Integer integer = integerHashMap.get(title);
        System.out.println(integer);
        itempanel.setBounds(0,integer,840,55);
        integer+=60;
        integerHashMap.replace(title,integer);
        itempanel.add(panelL);
        itempanel.add(jButton);
        JPanel jPanel = hashMap.get(title);
        jPanel.add(itempanel);
        jPanel.updateUI();
        Dimension dimension1 = new Dimension(840, integer);
        jPanel.setPreferredSize(dimension1);
        socketList.forEach(socket->{  //发送
            try {
                OutputStream outputStream = socket.getOutputStream();
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
                PrintWriter printWriter = new PrintWriter(outputStreamWriter);
                printWriter.println(sendtext);
                printWriter.flush();
            } catch (SocketException e) {
                System.out.println(1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        jtf.setText(""); //清空
    }
    class receive implements Runnable{
        List<Socket> socketList;
        public receive(List<Socket> socketList) {
            this.socketList = socketList;
        }
        @Override
        public void run() {
            ServerSocket serverSocket=null;
            try {
                serverSocket=new ServerSocket(8888);
                System.out.println("监听客户端的连接");
                while (true){
                    Socket socketx=serverSocket.accept();
                    socketList.add(socketx);
                    new Thread(new HandleSocket(socketx,socketList)).start();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    class ShouFile implements Runnable{
        Socket socket;
        List<Socket> socketList;
        public ShouFile(Socket socket, List<Socket> socketList) {
            this.socket = socket;
            this.socketList = socketList;
        }
        @Override
        public void run() {
            while (true){
                try {
                    System.out.println("Thread running>>>");
                    InputStream inputStream = socket.getInputStream();
                    DataInputStream dis = new DataInputStream(inputStream);
                    long length=dis.readLong();
                    String name=dis.readUTF(); //客户端传输信息
                    System.out.println(name);
                    String[] split = name.split("@");
                    int cntName=Integer.parseInt(split[0]); //客户端姓名长度
                    String ClentName=split[1]; //客户端姓名
                    String CnameL=ClentName.substring(ClentName.length()-2);
                    String Filename=split[2]; //客户端传输文件名
                    String text="接收文件《"+Filename+"》，自动保存在D:\\BigProgram目录下！";
                    JLabel msglabel=new JLabel(text+System.lineSeparator());
                    msglabel.setFont(new Font("微软雅黑",Font.BOLD,18));
                    msglabel.setForeground(Color.BLACK);
                    msglabel.setBackground(Color.WHITE);
                    msglabel.setSize(840,30);
                    msglabel.setOpaque(true);
                    FlowLayout flowLayout = new FlowLayout(); //消息面板
                    JPanel itempanel=new JPanel(flowLayout);
                    FlowLayout layout=(FlowLayout)itempanel.getLayout();
                    layout.setAlignment(FlowLayout.LEFT);
                    JButton jButton1=new RoundButton(CnameL);
                    Insets insets = new Insets(-5, -5, -5, -5);
                    jButton1.setMargin(insets);
                    Font font = new Font("微软雅黑", Font.BOLD, 18);
                    jButton1.setFont(font);
                    Dimension dimension = new Dimension(48, 48);
                    jButton1.setPreferredSize(dimension);
                    jButton1.setBackground(Color.BLUE);
                    jButton1.setForeground(Color.WHITE);
                    GridLayout gridLayout = new GridLayout(2, 1);
                    JPanel jPanel1=new JPanel(gridLayout);
                    JLabel label1=new JLabel(ClentName);
                    jPanel1.add(label1);
                    jPanel1.add(msglabel);
                    Color color = new Color(241, 241, 241);
                    itempanel.setBackground(color);
                    Integer integer = integerHashMap.get(ClentName);
                    itempanel.setBounds(0,integer,840,55);
                    integer+=60;
                    integerHashMap.replace(ClentName,integer);
                    itempanel.add(jButton1);
                    itempanel.add(jPanel1);
                    JPanel jPanel = hashMap.get(ClentName);
                    jPanel.add(itempanel);
                    jPanel.updateUI();
                    Dimension dimension1 = new Dimension(840, integer);
                    jPanel.setPreferredSize(dimension1);
                    hashMap.replace(ClentName,jPanel);
                    int tabCount = tabbedPane1.getTabCount();
                    int index = 0;
                    int selectedIndex = tabbedPane1.getSelectedIndex();
                    for(int i=0;i<tabCount;i++){
                        if(tabbedPane1.getTitleAt(i).contains(ClentName)){
                            index=i;
                            break;
                        }
                    }
                    if(selectedIndex!=index){
                        String title = tabbedPane1.getTitleAt(index);
                        if(title.equals(ClentName)){
                            tabbedPane1.remove(index);
                            JScrollPane jsp = new JScrollPane();
                            Dimension dimension2 = new Dimension(840, 400);
                            jsp.setPreferredSize(dimension2);
                            jsp.getViewport().add(jPanel);
                            jsp.validate();
                            tabbedPane1.insertTab(ClentName+"(1)",null,jsp,null,index);
                        }else {
                            System.out.println(title);
                            String x=title.substring(title.indexOf('(')+1);
                            System.out.println(x);
                            String y=x.substring(0,x.indexOf(')'));
                            System.out.println(y);
                            Integer value = Integer.valueOf(y);
                            value=value+1;
                            tabbedPane1.remove(index);
                            JScrollPane jsp = new JScrollPane();
                            Dimension dimension2 = new Dimension(800, 400);
                            jsp.setPreferredSize(dimension2);
                            jsp.getViewport().add(jPanel);
                            jsp.validate();
                            tabbedPane1.insertTab(ClentName+"("+value+")",null,jsp,null,index);
                        }
                    }
                    File file = new File("D:\\BigProgram\\" + (int) (Math.random() * 100) + Filename);
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    DataOutputStream dos=new DataOutputStream(fileOutputStream);
                    int count=-1,sum=0;
                    byte[] buffer=new byte[1024*1024];
                    while((count=dis.read(buffer))!=-1){
                        dos.write(buffer,0,count);
                        sum+=count;
                        System.out.println("已结收" + sum + "比特");
                        if(sum==length)
                            break;
                    }
                    dos.flush();
                }catch (Exception e){
                    socketListFile.remove(socket);
                    e.printStackTrace();
                    break;
                }
            }
        }
    }
    class HandleSocket implements Runnable{
        Socket socket;
        List<Socket> socketList;
        public HandleSocket(Socket socket, List<Socket> socketList) {
            this.socket = socket;
            this.socketList = socketList;
        }
        @Override
        public void run() {
            BufferedReader bufferedReader=null;
            try {
                InputStream inputStream = socket.getInputStream(); // 读取客户端发来的数据
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                bufferedReader = new BufferedReader(inputStreamReader);
                System.out.println("等待读取客户端：" + socket.getLocalAddress().toString().substring(1) + ":" + socket.getPort() + " 的消息");
                while (true) {
                    String clientInfo = bufferedReader.readLine(); //发送姓名格式如：2陈标@
                    int len1=Integer.parseInt(clientInfo.substring(0,1)); //名字长度
                    String name1 = clientInfo.substring(1, len1 + 1); //名字
                    if(clientInfo.substring(clientInfo.length()-1).equals("@")){
                        ipAndname.put(socket.getLocalAddress().toString().substring(1)+":"+socket.getPort(),name1);
                        System.out.println(clientInfo);
                        JScrollPane jScrollPane=new JScrollPane();
                        Dimension dimension = new Dimension(840, 400);
                        jScrollPane.setPreferredSize(dimension);
                        JPanel panel=new JPanel(null);
                        Color color = new Color(250, 250, 250);
                        panel.setBackground(color);
                        panel.setVisible(true);
                        jScrollPane.getViewport().add(panel);
                        hashMap.put(name1,panel);
                        tabbedPane1.addTab(name1,jScrollPane);
                        integerHashMap.put(name1,0);
                        continue;
                    }
                    int len=Integer.parseInt(clientInfo.substring(0,1)); //名字长度  //将读取数据拼接到文本域显示
                    String name = clientInfo.substring(1, len + 1); //名字
                    String nameL=name.substring(name.length()-2);
                    String text = clientInfo.substring(len + 1); //内容
                    JLabel msglabel=new JLabel(text+System.lineSeparator());
                    Font font = new Font("微软雅黑", Font.BOLD, 18);
                    msglabel.setFont(font);
                    msglabel.setForeground(Color.BLACK);
                    msglabel.setBackground(Color.WHITE);
                    msglabel.setSize(840,30);
                    msglabel.setOpaque(true);
                    FlowLayout flowLayout = new FlowLayout(); //消息面板
                    JPanel itempanel=new JPanel(flowLayout);
                    FlowLayout layout=(FlowLayout)itempanel.getLayout();
                    layout.setAlignment(FlowLayout.LEFT);
                    JButton jButton1=new RoundButton(nameL);
                    Insets insets = new Insets(-5, -5, -5, -5);
                    jButton1.setMargin(insets);
                    Font font1 = new Font("微软雅黑", Font.BOLD, 18);
                    jButton1.setFont(font1);
                    Dimension dimension = new Dimension(48, 48);
                    jButton1.setPreferredSize(dimension);
                    jButton1.setBackground(Color.BLUE);
                    jButton1.setForeground(Color.WHITE);
                    GridLayout gridLayout = new GridLayout(2, 1);
                    JPanel jPanel1=new JPanel(gridLayout);
                    JLabel label1=new JLabel(name);
                    jPanel1.add(label1);
                    jPanel1.add(msglabel);
                    Color color = new Color(250, 250, 250);
                    itempanel.setBackground(color);
                    Integer integer = integerHashMap.get(name);
                    itempanel.setBounds(0,integer,840,55);
                    integer+=60;
                    integerHashMap.replace(name,integer);
                    itempanel.add(jButton1);
                    itempanel.add(jPanel1);
                    JPanel jPanel = hashMap.get(name);
                    jPanel.add(itempanel);
                    jPanel.updateUI();
                    Dimension dimension1 = new Dimension(840, integer);
                    jPanel.setPreferredSize(dimension1);
                    hashMap.replace(name,jPanel);
                    int tabCount = tabbedPane1.getTabCount();
                    int index = 0;
                    int selectedIndex = tabbedPane1.getSelectedIndex();
                    for(int i=0;i<tabCount;i++){
                        if(tabbedPane1.getTitleAt(i).contains(name)){
                            index=i;
                            break;
                        }
                    }
                    if(selectedIndex!=index){
                        String title = tabbedPane1.getTitleAt(index);
                        if(title.equals(name)){
                            tabbedPane1.remove(index);
                            JScrollPane jsp = new JScrollPane();
                            Dimension dimension2 = new Dimension(840, 400);
                            jsp.setPreferredSize(dimension2);
                            jsp.getViewport().add(jPanel);
                            jsp.validate();
                            tabbedPane1.insertTab(name+"(1)",null,jsp,null,index);
                        }else {
                            System.out.println(title);
                            String x=title.substring(title.indexOf('(')+1);
                            System.out.println(x);
                            String y=x.substring(0,x.indexOf(')'));
                            System.out.println(y);
                            Integer value = Integer.valueOf(y);
                            value=value+1;
                            tabbedPane1.remove(index);
                            JScrollPane jsp = new JScrollPane();
                            Dimension dimension2 = new Dimension(800, 400);
                            jsp.setPreferredSize(dimension2);
                            jsp.getViewport().add(jPanel);
                            jsp.validate();
                            tabbedPane1.insertTab(name+"("+value+")",null,jsp,null,index);
                        }
                    }
                    System.out.println(socket.getLocalAddress().toString().substring(1) + ":" + socket.getPort() + "发送的消息是：" + clientInfo);
                }
            } catch (SocketException e) {
                System.out.println(socket.getLocalAddress().toString().substring(1) + ":" + socket.getPort() + "断开连接");  // 强制关闭连接后的处理
                String names = ipAndname.get(socket.getLocalAddress().toString().substring(1) + ":" + socket.getPort());
                System.out.println(names);
                int count = tabbedPane1.getTabCount();
                int a=0;
                for(int i=0;i<count;i++){
                    if(tabbedPane1.getTitleAt(i).contains(names)){
                        a=i;
                        break;
                    }
                }
                tabbedPane1.remove(a);
                socketList.remove(socket); // 将该连接从socketList中移除
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            }
        }
    }
}